package com.wash.car.web.controller.admin;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.pmo.boot.common.BizException;
import com.pmo.boot.common.api.BaseResult;
import com.pmo.boot.common.api.DefaultResult;
import com.wash.car.biz.AdminUserServer;
import com.wash.car.dao.domain.AdminUserDomain;
import com.wash.car.web.config.CacheConfiguration;
import com.wash.car.web.config.context.UserContext;
import com.wash.car.web.config.context.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@Api(tags = {"登录管理"})
@RestController
@RequestMapping(path = "/admin")
public class AdminLogInController {

    @Autowired
    private AdminUserServer adminUserServer;

    @ApiOperation(value = "登录")
    @PostMapping(path = "login")
    public DefaultResult<AdminLoginReturnModel> login(@RequestBody AdminLoginModel model) {
        AdminUserDomain dbAdminUserDomain = adminUserServer.login(model.getUsername(), model.getPassword());
        if (ObjectUtil.isEmpty(dbAdminUserDomain)) {
            throw BizException.error("1402", "用户名或密码错误！");
        }
        String token = IdUtil.fastSimpleUUID();
        CacheConfiguration.add(token, new UserInfo().setToken(token).setUserId(dbAdminUserDomain.getId()).setIsAdmin(1));
        return DefaultResult.success(new AdminLoginReturnModel().setToken(token));
    }


    @ApiOperation(value = "推出")
    @PostMapping(path = "quit")
    public BaseResult quit() {
        CacheConfiguration.del(UserContext.get().getToken());
        return BaseResult.success();
    }


    @Data
    static class AdminLoginModel {
        @ApiModelProperty(value = "账号", required = true)
        private String username;
        @ApiModelProperty(value = "密码", required = true)
        private String password;
    }

    @Data
    static class AdminLoginReturnModel {
        @ApiModelProperty(value = "登录token")
        private String token;

    }
}
